/*
 * 创建日期 2004-9-26
 *
 * 更改所生成文件模板为
 * 窗口 > 首选项 > Java > 代码生成 > 代码和注释
 */
package com.ctsi.commons.util.crypto;

import com.ctsi.commons.util.UtilFile;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.security.NoSuchAlgorithmException;

/**
 * @author Administrator
 * 
 *         更改所生成类型注释的模板为 窗口 > 首选项 > Java > 代码生成 > 代码和注释
 */
public class BlowFishCrypt {

	private SecretKeySpec secretKeySpec = null;

	/**
	 * 构造
	 * 
	 * @param secretKeySpec
	 *            A SecretKeySpec object.
	 */
	public BlowFishCrypt(SecretKeySpec secretKeySpec) {
		this.secretKeySpec = secretKeySpec;
	}

	/**
	 * 构造
	 * 
	 * @param key
	 *            An encoded secret key
	 */
	public BlowFishCrypt(byte[] key) {
		try {
			secretKeySpec = new SecretKeySpec(key, "Blowfish");
		} catch (Exception e) {
		}
	}

	/**
	 * 构造
	 * 
	 * @param keyFile
	 *            保存的key
	 */
	public BlowFishCrypt(File keyFile) {
		try {

			secretKeySpec = new SecretKeySpec(UtilFile.readBytes(keyFile), "Blowfish");
		} catch (Exception e) {
		}
	}

	/**
	 * 加密字符串
	 * 
	 * @param string
	 *            The string to encrypt.
	 */
	public byte[] encrypt(String string) {

			return encrypt(string.getBytes(StandardCharsets.UTF_8));

	}

	/**
	 * 加密
	 * 
	 * @param bytes
	 *            The array of bytes to encrypt.
	 */
	public byte[] encrypt(byte[] bytes) {
		byte[] resp = null;

		try {
			resp = crypt(bytes, Cipher.ENCRYPT_MODE);
		} catch (Exception e) {
			return null;
		}
		return resp;
	}

	/**
	 * 解密
	 * 
	 * @param bytes
	 *            The array of bytes to decrypt.
	 */
	public byte[] decrypt(byte[] bytes) {
		byte[] resp = null;

		try {
			resp = crypt(bytes, Cipher.DECRYPT_MODE);
		} catch (Exception e) {
			return null;
		}
		return resp;
	}

	private byte[] crypt(byte[] bytes, int mode) throws Exception {
		if (secretKeySpec == null)
			throw new Exception("SecretKey cannot be null.");
		Cipher cipher = Cipher.getInstance("Blowfish");

		cipher.init(mode, secretKeySpec);
		return cipher.doFinal(bytes);
	}

	public static byte[] generateKeyEncoded() throws NoSuchAlgorithmException {

		SecretKey secretKey = generateKey();
		byte[] keyBytes = secretKey.getEncoded();

		return keyBytes;
	}

	public static SecretKey generateKey() throws NoSuchAlgorithmException {
		KeyGenerator keyGen = KeyGenerator.getInstance("Blowfish");
		keyGen.init(448);

		SecretKey secretKey = keyGen.generateKey();
		return secretKey;

	}

}
